Pow(x, n) Algorithm
The Pow(x, n) algorithm, also known as the Exponentiation by Squaring algorithm, is an efficient method for calculating the power of a number, i.e., x^n, where x is the base and n is the exponent. This algorithm is based on the idea of repeated squaring, which reduces the number of multiplications required to compute the result. The algorithm takes advantage of the fact that the exponent can be represented as a binary number, allowing for a more efficient calculation by breaking down the problem into smaller subproblems.
The Pow(x, n) algorithm works in a recursive or iterative manner, depending on the implementation. In the recursive approach, the algorithm checks if the exponent is even or odd. If the exponent is even, the algorithm calculates x^(n/2) recursively and returns the square of the result. If the exponent is odd, the algorithm calculates x^((n-1)/2) recursively and returns the result multiplied by the base x. In the iterative approach, the algorithm initializes the result as 1 and iterates through each bit of the binary representation of the exponent, starting from the most significant bit. If the current bit is 1, the result is multiplied by the base raised to the power of 2^i, where i is the position of the bit. In each iteration, the base is squared, effectively reducing the number of multiplications required. This makes the Pow(x, n) algorithm more efficient than the naive approach of multiplying the base by itself n times.
class Solution {
public:
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
double result = 1.0;
bool negative = false;
if (n < 0) negative = true;
while (n) {
if (n & 1)
result *= x;
x *= x;
n /= 2;
}
return negative ? (1.0 / result) : result;
}
};